import {Component, OnInit, AfterViewInit} from '@angular/core';
import {ModalController, NavParams} from '@ionic/angular';
import {Router} from '@angular/router';
import {AppGlobalService} from '../../shared/service/app-global.service';
import {CityModalComponent} from '../city-modal/city-modal.component';
import {HttpService} from '../../shared/service/http.service';
import { Picker } from 'ng-zorro-antd-mobile';


declare var BMap;

@Component({
    selector: 'app-map-show',
    templateUrl: './map-show.component.html',
    styleUrls: ['./map-show.component.scss'],
    providers:[Picker]
})
export class MapShowComponent implements OnInit, AfterViewInit {
    data: any;  // 与主页面进行交互的参数
    mapId: any;  // 地图显示
    map:any;    // 地图显示
    districts: any = [{label: '请选择', code: 0}];   // 区域
    tradArea: any = [{label: '请选择', code: 0}];    // 片区
    selectTradArea: any = {label: '请选择', code: 0};    // 选中的片区
    selectCity: any = {label: '请选择', code: 0};    // 选中的城市
    selectDistrict: any = {label: '请选择', code: 0};    // 选中的区域
    dataPoint: any;     // 初始的point
    address:any;    // 地址
    clicked:boolean = false;    // 是否已经点击过地图

    constructor(private navParams: NavParams,
                private modalCtrl: ModalController,
                public router: Router,
                private appGlobalService: AppGlobalService,
                private http: HttpService) {
        this.mapId = 'mapId' + new Date().getTime();
    }

    ngOnInit() {
        this.data = JSON.parse(this.navParams.data.value);
        console.log(this.data, 'mapdata');
        // let addressStr = "深圳市，南山区，南油";
        this.clicked = this.data.point.lng.toString().indexOf('##') === -1?true:false;
        this.dataPoint = this.data.point.lng.toString().indexOf('##') === -1?this.data.point : {lng: 116.404, lat: 39.915};
        if(this.clicked){
            let addressStr = this.data.jointName;
            let code = this.data.code;
            this.address = this.data.address;
            let addressArr = addressStr.split(',')
            this.selectCity = {code:code.substr(0,4),name:addressArr[0]};
            this.openDistrict(this.selectCity.code, this.selectCity.name); 
            this.selectDistrict = {code:code.substr(0,6), name:addressArr[1]};
            this.openDistrict(this.selectDistrict.code, this.selectDistrict.name); 
            this.selectTradArea = {code:code.substr(0,8), name:addressArr[2]};
            this.data.jointName = this.selectCity.name + ',' + this.selectDistrict.name + ',' + this.selectTradArea.name
        }
    }

    ngAfterViewInit() {
        let that = this;
        setTimeout(function () {
            that.showMap(that.dataPoint);
        }, 100);
    }

    // 打开城市选择模态框
    async openCity() {
        const that = this;
        let valueobj = {table: this.data.table, id: this.data.id};
        const modal = await this.modalCtrl.create({
            component: CityModalComponent,
            componentProps: {value: JSON.stringify(valueobj)}
        });

        modal.onDidDismiss().then(function (data) {
            that.selectCity = data.data||{label: '请选择', code: 0};
            if(that.selectCity.code){
                that.openDistrict(that.selectCity.code, that.selectCity.name);      // 根据选中的城市，获取相应的区域
                that.addressToPoint(that.selectCity.name);
            }
        });
        return await modal.present();
    }

    // 打开区域或片区的选择框，并加载数据
    openDistrict(code, name) {
        this.data.table.condition = [{field: 'parent_id', value: code}];
        const table = {
            'table': this.data.table
        };
        let keyword = this.selectCity.name;
        this.data.jointName = this.selectCity.name
        if (code.toString().length === 6) {
            keyword = this.selectCity.name + name;
            this.data.jointName = this.selectCity.name + ',' + name
        } else if(code.toString().length === 8){
            keyword = this.selectCity.name + this.selectDistrict.name + this.selectTradArea.name;
            this.data.jointName = this.selectCity.name + ',' + this.selectDistrict.name + ',' + this.selectTradArea.name
        }
        const params = {
            content: table,
            id: this.data['id'],
            // sessionId:"6081a798-1a7f-43e3-87c5-a71c6edff61c"
            sessionId: localStorage.getItem('sessionId')
        };
        this.http.post('application/submit', params, res => {
            let result = res.data.data;
            if (result) {
                result.unshift({label: '请选择', code: 0});
                if (code.toString().length === 4) {
                    this.districts = result;
                    this.districts.forEach(element => {
                        element.label = element.name
                    });
                    console.log(this.districts,'dseeeerrrrr')
                } else if (code.toString().length === 6) {
                    this.tradArea = result;
                    this.tradArea.forEach(element => {
                        element.label = element.name
                    });
                    this.districts.forEach(element => {
                        if(element.code === code){
                            element.children = this.tradArea;
                        } 
                    });
                }
            } else {
                this.appGlobalService.showToast(res['message'], 2000, 'middle');
            }
        });
        this.addressToPoint(keyword);
        // this.data.address = keyword;
        this.data.code = code
    }

    name4="请选择"
    onPickerChange(event){
        console.log('pppp',event);
        if(!event[0].children||event[0].children.length<2){
            this.openDistrict(event[0].code, event[0].label)
        }
        
    }
    onOk4(event){
        console.log('ok',event);
        this.name4=this.data.jointName
    }
    value:any;
    dataval:any = [{label:"春", code:"001",children:[{label:"夏1", code:"01"},{label:"秋2",code:"02"}]},{label:"夏", code:"002"},{label:"秋",code:"003"}];

    // 关闭模态框并传参
    dismiss() {
        this.modalCtrl.dismiss(this.data);
    }

    changeAddress(){
        if(!this.clicked){
            let keyword = this.selectCity.name + this.selectDistrict.name + this.selectTradArea.name + this.address;
            this.addressToPoint(keyword);
            this.data.address = this.address;
        }     
    }

    // select显示选中的元素
    compare(itemOne, itemTwo) {
        return itemOne && itemTwo && itemOne.code == itemTwo.code;
    }

    showMap(poi) {
        let map = new BMap.Map(this.mapId);
        this.map = map;
        // let pointcode = {lng: 116.404, lat: 39.915};
        let pointCode = poi;
        map.addEventListener('touchend', e => {
            this.clicked = true;
            pointCode = {
                lng: e.point.lng,
                lat: e.point.lat
            }
            let point = new BMap.Point(pointCode.lng, pointCode.lat);
            //清除之前标注
            map.clearOverlays();
            let marker = new BMap.Marker(point);
            map.addOverlay(marker);
            this.pointToAddress(point);
            this.data.point = pointCode;
        })
        let point = new BMap.Point(pointCode.lng, pointCode.lat);
        let marker = new BMap.Marker(point);
        map.centerAndZoom(point, 18);
        map.enableScrollWheelZoom(true);
        map.enableContinuousZoom(); // 连续缩放效果，默认禁用
        if(this.clicked){
            map.addOverlay(marker);
        }
    }

    // 将地址解析成经纬度
    addressToPoint(keyword) {
        let that = this;
        let geo = new BMap.Geocoder();
        geo.getPoint(keyword, function (point) {
            that.showMap(point);
        });
    }

    // 将经纬度解析成地址
    pointToAddress(point){
        let that = this;
        let geo = new BMap.Geocoder();
        geo.getLocation(point, function (obj) {
            console.log(obj,'objwwwww')
            that.address = obj.addressComponents.street + obj.addressComponents.streetNumber;
            that.data.address = that.address;
        });
    }
}
